﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Commons.Entity.CommonEnums;
using Commons.Entity;
using Common.Background.Data;
using System.Transactions;
using EF.Commons.Background.Entity;

namespace Common.Background.Service
{
    public partial class SystemServices : ServiceBase, ISystemServices, IWebManageMenus
    {
        const string ALLSELECT = "-1";
        const string COMPANYSELECT = "0";
        List<WebManageMenus> WebManageMenusCache = new WebManageMenusRepository().GetModel().ToList();

        #region 员工管理

        public void WebManageUserAdd(WebManageUsers webManageUser)
        {

            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    webManageUser.ManageUserID = new PKIDTableRepository().GetNewPKID(PKIDTable.WebManageUsers);
                    webManageUser.CreateDate = DateTime.Now;
                    webManageUser.UpdateDate = DateTime.Now;
                    webManageUser.Status = (int)Status.Normal;
                    webManageUser.IntroductionURL = webManageUser.IntroductionURL ?? string.Empty;
                    webManageUser.Operator = string.IsNullOrEmpty(webManageUser.Operator)
                       ? "匿名"
                       : webManageUser.Operator;
                    webManageUser.WebManageUser_WebManageRoles_Extend.ToList().ForEach(i =>
                    {
                        i.ManageUserID = webManageUser.ManageUserID;
                    });
                    base.iWebManageUsersRepository.Insert(webManageUser);
                    base.iWebManageUser_WebManageRolesRepository.Insert(webManageUser.WebManageUser_WebManageRoles_Extend.ToList());
                    trans.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }
        }

        public void WebManageUserModify(WebManageUsers webManageUser)
        {
            var webManageUser_WebManageRoles = webManageUser.WebManageUser_WebManageRoles_Extend.ToList<WebManageUser_WebManageRoles>();
            using (var trans = new TransactionScope())
            {
                try
                {
                    #region 用户表
                    base.iWebManageUsersRepository.Update(webManageUser);
                    #endregion
                    #region 用户权限关系表，先删除再插入
                    new WebManageUser_WebManageRolesRepository().DeleteForUserID(webManageUser.ManageUserID);
                    base.iWebManageUser_WebManageRolesRepository.Insert(webManageUser_WebManageRoles);
                    #endregion
                    trans.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }

        }

        public void WebManageUserModify(List<WebManageUsers> webManageUsers)
        {
            webManageUsers.ForEach(item =>
                {
                    item.UpdateDate = DateTime.Now;
                });
            base.iWebManageUsersRepository.Update(webManageUsers);

        }

        public void WebManageUsersDelete(List<WebManageUsers> webManageUsers)
        {
            iWebManageUsersRepository.Delete(webManageUsers);
        }

        public WebManageUsers GetWebManageUsers(WebManageUsers webManageUser)
        {
            return new WebManageUsersRepository()
                .GetDetailModel()
                .SingleOrDefault(i => i.ManageUserID == webManageUser.ManageUserID) as WebManageUsers;
        }

        public WebManageUsers GetWebManageUsers(int userID)
        {
            return iWebManageUsersRepository.GetEntity<WebManageUsers>(userID);
        }


        public PagedList<WebManageUsers> GetWebManageUsers(VPredication vp, PagingParam pp)
        {
            var linq = from data in base.iWebManageUsersRepository.GetEntities<WebManageUsers>()
                       join data2 in base.iWebDepartmentsRepository.GetEntities<WebDepartments>()
                       on data.DepartmentID equals data2.DepartmentID
                       join data3 in iWebManageUser_WebManageRolesRepository.GetDetailModel()
                       on data.ManageUserID equals data3.ManageUserID into list
                       select new WebManageUsers_Ext
                       {
                           ManageUserID = data.ManageUserID,
                           LoginName = data.LoginName,
                           Password = data.Password,
                           RealName = data.RealName,
                           Gender = data.Gender,
                           Phone = data.Phone,
                           Mobile = data.Mobile,
                           Email = data.Email,
                           QQ = data.QQ,
                           MSN = data.MSN,
                           Rtx = data.Rtx,
                           Birthday = data.Birthday,
                           Description = data.Description,
                           DepartmentID = data.DepartmentID,
                           CreateDate = data.CreateDate,
                           UpdateDate = data.UpdateDate,
                           Operator = data.Operator,
                           Status = data.Status,
                           WebDepartments_Extend = data2,
                           WebManageUser_WebManageRoles_Extend = list,
                       };

            if (vp.ContainsKey("name"))
            {
                if (!string.IsNullOrEmpty(Convert.ToString(vp["name"])))
                {
                    int yy = 0;
                    int.TryParse(vp["name"].ToString(), out yy);
                    linq = linq.Where(item => item.RealName.Contains(vp["name"].ToString().Trim())
                        || item.LoginName.Contains(vp["name"].ToString().Trim())
                        || item.ManageUserID == yy
                        || item.LoginName.Contains(vp["name"].ToString().Trim()));
                }
            }
            if (vp.ContainsKey("departmentID"))
            {
                linq = linq.Where(item => item.DepartmentID == Convert.ToInt32(vp["departmentID"].ToString()));
            }
            if (vp.ContainsKey("roleID"))
            {
                if (!string.IsNullOrEmpty(Convert.ToString(vp["roleID"])) && Convert.ToString(vp["roleID"]) != "-1")
                {
                    int[] linquser = base.iWebManageUser_WebManageRolesRepository
                                         .GetEntities<WebManageUser_WebManageRoles>()
                                         .Where(item => item.ManageRoleID == Convert.ToInt32(vp["roleID"].ToString()))
                                         .Select(item => item.ManageUserID).ToArray();
                    linq = linq.Where(item => linquser.Contains(item.ManageUserID)); //从集合里找某个整数是否在其中
                }
            }

            return new PagedList<WebManageUsers>(linq, pp.PageIndex, pp.PageSize);
        }


        #region  查询职员
        /// <summary>
        /// 查询职员
        /// </summary>
        /// <param name="WebManageUsers">DepartmentId(是负(全部查),是正(准确查))</param>
        /// RealName，LoginName,是null全部查  
        /// WebManageRoles关联查
        /// <param name="vp"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public PagedList<WebManageUsers> WebManageUsersList(VPredication vp, PagingParam pp)
        {
            var linq = base.iWebManageUsersRepository.GetModel();

            return new PagedList<WebManageUsers>(linq, pp.PageIndex, pp.PageSize);

        }
        #endregion

        //#region 部门和职位
        public WebDepartments GetWebDepartments(WebDepartments webDepartment)
        {
            return base.iWebDepartmentsRepository.GetEntity<WebDepartments>(webDepartment.DepartmentID);
        }

        public List<WebDepartments> GetWebDepartments(VPredication vp)
        {
            var linq = iWebDepartmentsRepository.GetEntities<WebDepartments>();
            return linq.ToList();
        }
        public List<WebManageRoles> GetWebManageRoles(WebDepartments webDepartment)
        {
            var linq = base.iWebManageRolesRepository.GetEntities<WebManageRoles>()
                           .Where(item => item.DepartmentID == webDepartment.DepartmentID);
            return linq.ToList();
        }

        public List<WebManageUser_WebManageRoles> GetWebManageUser_WebManageRoles(WebManageUsers WebManageUser)
        {
            var linq = base.iWebManageUser_WebManageRolesRepository.GetDetailModel()
                           .Where(item => item.ManageUserID == WebManageUser.ManageUserID);
            return linq.ToList<WebManageUser_WebManageRoles>();
        }
        #endregion

        #region ISystemServices 成员

        /// <summary>
        /// 根据角色类型，得到角色列表
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public List<WebManageRoles> GetRolesByStatus(UserOperatorRole status)
        {
            return base.iWebManageRolesRepository.GetModel().Where(item => item.Status == (int)status).ToList();
        }


        #region 菜单树
        public List<WebManageMenus> WebManageMenusList(WebManageMenus WebManageMenus, VPredication vp)
        {
            return base.iWebManageMenusRepository
                       .GetModel()
                       .OrderBy(item => item.SortNumber).ToList();
        }

        public WebManageMenus WebManageMenusTree()
        {
            WebManageMenus WebManageMenu = new WebManageMenus() { MenuID = 0 };
            WebManageMenu.SubWebManageMenus = WebManageMenusTree(WebManageMenu);
            return WebManageMenu;
        }

        public List<WebManageMenus> WebManageMenusTree(WebManageMenus WebManageMenus)
        {
            return (from _objWMMR in WebManageMenusCache
                    where _objWMMR.ParentID == WebManageMenus.MenuID
                    select new WebManageMenus_Ext
                    {
                        MenuID = _objWMMR.MenuID,
                        MenuName = _objWMMR.MenuName,
                        SortNumber = _objWMMR.SortNumber,
                        LinkUrl = _objWMMR.LinkUrl,
                        MenuLevel = _objWMMR.MenuLevel,
                        SubWebManageMenus = WebManageMenusTree(_objWMMR),
                        About = _objWMMR.About
                    }
            ).ToList<WebManageMenus>();
        }
        #endregion

        #region 得到菜单
        public WebManageMenus GetWebManageMenus(WebManageMenus WebManageMenus)
        {
            return base.iWebManageMenusRepository.Find(WebManageMenus.MenuID);
        }
        #endregion

        #region 设置菜单
        public void SetWebManageMenus(WebManageMenus WebManageMenus)
        {
            WebManageMenus.UpdateDate = DateTime.Now;
            base.iWebManageMenusRepository.Update(WebManageMenus);
        }
        #endregion

        #region 添加列表
        public void AddWebManageMenus(WebManageMenus WebManageMenus)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    WebManageMenus.Operator = string.Empty;
                    WebManageMenus.MenuID = new PKIDTableRepository().GetNewPKID(PKIDTable.WebManageMenus);
                    if (WebManageMenus.ParentID == 0)
                        WebManageMenus.MenuLevel = 1;
                    else
                    {
                        WebManageMenus.MenuLevel = base.iWebManageMenusRepository
                                           .GetModel()
                                                .Where(i => i.MenuID == WebManageMenus.ParentID)
                                                       .First().MenuLevel + 1;
                    }
                    WebManageMenus.UpdateDate = DateTime.Now;
                    iWebManageMenusRepository.Insert(WebManageMenus);
                    trans.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    trans.Dispose();
                }
            }

        }
        #endregion

        #region  删除菜单
        public void DeleteManageMenus(WebManageMenus WebManageMenus)
        {
            base.iWebManageMenusRepository.Delete(iWebManageMenusRepository.Find(WebManageMenus.MenuID));
        }
        #endregion

        #endregion
    }
}
